import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";
import { PxButton } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

dayjs.extend(isToday);

export const formatSpanFn = (data: Array<any>): Array<any> => {
  if (!data?.length) return [];
  let currentGasNameNum = 0;
  let currentStationNum = 0;
  let currentGasName = "";
  let currentGasNameIndex = 0;
  data?.forEach((item, index, arr) => {
    const { gasName, station } = item;
    if (index === 0) {
      currentGasName = gasName;
      currentGasNameIndex = 0;
    } else if (gasName !== currentGasName) {
      currentGasName = gasName;
      currentGasNameIndex++;
    }
    item["index"] = currentGasNameIndex;
    currentGasNameNum++;
    currentStationNum++;
    if (gasName !== arr[index + 1]?.gasName) {
      data[index - currentGasNameNum + 1]["rowspan"] = currentGasNameNum;
      currentGasNameNum = 0;
      data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
      currentStationNum = 0;
    } else {
      if (station !== arr[index + 1]?.station) {
        data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
        currentStationNum = 0;
      }
    }
  });
  return data;
};

export const formatBottomTableDataFn = (formatSpanData: Array<any>, gasCheckInfoResDTOList: Array<any>, scheduleEmployeeInfoDTOList: Array<any>) => {
  const inspectionPerson = {
    gasName: "点检人",
    isInspectionPerson: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  const systemEngineer = {
    gasName: "系统工程师",
    isSystemEngineer: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  formatSpanData[0]?.dayValues?.forEach((item, index) => {
    const { planTimeDayStr = "" } = item;
    const t = gasCheckInfoResDTOList?.find(item => item?.itemDate === planTimeDayStr);
    if (t) {
      const { checkerInfo = null, engineerInfo = null, itemDate = "" } = t;
      const checkerInfoArr = [checkerInfo?.operator, checkerInfo?.operatorName]?.filter(item => !!item);
      const engineerInfoArr = [engineerInfo?.operator, engineerInfo?.operatorName]?.filter(item => !!item);
      inspectionPerson[`readValue_f_${index}`] =
        checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
      if (dayjs(itemDate).isToday()) {
        inspectionPerson["inspectionPersonKey"] = `readValue_f_${index}`;
        inspectionPerson["itemDate"] = itemDate;
        systemEngineer["inspectionPersonName"] =
          checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
      }
      systemEngineer[`readValue_f_${index}`] =
        engineerInfoArr.length === 2 ? engineerInfoArr.join(" / ") : engineerInfoArr.length === 1 ? engineerInfoArr[0] : "";
      if (dayjs(itemDate).isToday()) {
        systemEngineer["systemEngineerKey"] = `readValue_f_${index}`;
        systemEngineer["itemDate"] = itemDate;
      }
    }
  });
  return [inspectionPerson, systemEngineer];
};

export const formatTableDataFn = (res: Record<string, any>): Array<any> => {
  const { recordItemResDTOList, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList } = res;
  if (!recordItemResDTOList?.length) return [];
  const formatData = recordItemResDTOList?.map(item => {
    const { dayValues = [], station = "" } = item;
    const ext = dayValues?.reduce((pre, cur, index, arr) => {
      const { supplyStatusL = "", supplyStatusR = "", valueDayHourList = [] } = cur;
      const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_BULK_CHECK_FIVE"); // 过滤当天 5：00
      const sd = valueDayHourList?.filter(item => item.groupCode === "GAS_BULK_CHECK_SEVENTEEN"); // 过滤当天 17：00
      pre[`readValue_f_${index}`] = fd[0]?.readValue;
      pre[`readValue_s_${index}`] = sd[0]?.readValue;
      pre[`supplyStatus_${index}`] = station === "L" ? supplyStatusL : station === "R" ? supplyStatusR : "";
      return pre;
    }, {});
    return { ...item, ...ext };
  });
  const formatSpanData = formatSpanFn(formatData);
  const formatBottomTableData = formatBottomTableDataFn(formatSpanData, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList);
  return [...formatSpanData, ...formatBottomTableData];
};

export const formatDateTableCloumnsFn = (data: Array<any>, cb: (scope: any) => void, cb2: (scope: any) => void): Array<any> => {
  if (!data?.length) return [];
  return data[0]?.dayValues?.reduce((pre, cur, index, arr) => {
    const { planTimeDayStr: label = "", valueDayHourList = [] } = cur;
    const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_BULK_CHECK_FIVE"); // 过滤当天 5：00
    const sd = valueDayHourList?.filter(item => item.groupCode === "GAS_BULK_CHECK_SEVENTEEN"); // 过滤当天 17：00
    const render = scope => {
      const {
        row: {
          isInspectionPerson = false,
          isSystemEngineer = false,
          inspectionPersonKey = "",
          systemEngineerKey = "",
          scheduleEmployeeInfoDTOList = [],
          inspectionPersonName = ""
        },
        column: { property = "" }
      } = scope;

      const styleFn = () => {
        const textAlign = isInspectionPerson || isSystemEngineer ? "center" : "left";
        const fontWeight = isInspectionPerson || isSystemEngineer ? 600 : undefined;
        return { textAlign, fontWeight };
      };

      const styleFn2 = () => {
        const textAlign = isInspectionPerson || isSystemEngineer ? "center" : "left";
        const fontWeight = isInspectionPerson || isSystemEngineer ? 600 : undefined;
        return { textAlign, fontWeight };
      };

      if (isInspectionPerson || isSystemEngineer) {
        const userInfo = localStorage.getItem("userInfo");
        const { userId = null } = JSON.parse(userInfo);
        if (inspectionPersonKey === property) {
          return () =>
            scope.row[property] ? (
              <div style={styleFn()}>{scope.row[property] || "--"}</div>
            ) : (
              <div style={styleFn2()}>
                <PxButton
                  type="primary"
                  size="small"
                  disabled={!scheduleEmployeeInfoDTOList?.some(item => item.userId === Number(userId))}
                  vHas={"GAS_CONSUMPTION_BULKGAS_INSPECTION_BTN"}
                  onClick={useThrottleFn(() => cb && cb(scope), delay)}
                >
                  {"点检"}
                </PxButton>
              </div>
            );
        } else if (systemEngineerKey === property) {
          return () =>
            scope.row[property] ? (
              <div style={styleFn()}>{scope.row[property] || "--"}</div>
            ) : (
              <div style={styleFn2()}>
                <PxButton
                  type="primary"
                  size="small"
                  disabled={!inspectionPersonName}
                  vHas={"GAS_CONSUMPTION_BULKGAS_INSPECTION_CONFIRM_BTN"}
                  onClick={useThrottleFn(() => cb2 && cb2(scope), delay)}
                >
                  {"确认"}
                </PxButton>
              </div>
            );
        } else {
          return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
        }
      } else {
        return () => <div style={styleFn()}>{scope.row[property] ?? "--"}</div>;
      }
    };
    const f = {
      label: fd[0]?.planTimeHourStr,
      prop: `readValue_f_${index}`,
      render
    };
    const s = {
      label: sd[0]?.planTimeHourStr,
      prop: `readValue_s_${index}`
    };
    const children = [f, s];
    const prop = "planTimeDayStr";
    const renderHeader = () => {
      return () => <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{label}</div>;
    };
    const d = { label, prop, renderHeader };
    d["children"] = children;
    pre.push(d);
    // const status = {
    //   label: "供应状态",
    //   prop: `supplyStatus_${index}`
    // };
    // pre.push(status);
    return pre;
  }, []);
};
